package com.deep.transaction.demo12.aop;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;

/**
 * 自定义事务的开启，提交，回滚
 */
@Component
@Slf4j
public class MyTransaction {

    @Autowired
    private DataSourceTransactionManager dataSourceTransactionManager;

    /**
     * 开启事务，并配置默认的事务传播机制
     *
     * @return
     */
    public TransactionStatus begin() {
        TransactionStatus transaction = dataSourceTransactionManager.getTransaction(new DefaultTransactionAttribute());
        log.info("事务开启成功");
        return transaction;
    }


    /**
     * 事务提交
     *
     * @param transaction
     */
    public void commit(TransactionStatus transaction) {
        log.info("事务提交成功");
        dataSourceTransactionManager.commit(transaction);
    }

    /**
     * 事务回滚
     *
     * @param transaction
     */
    public void rollback(TransactionStatus transaction) {
        log.info("事务回滚成功");
        dataSourceTransactionManager.rollback(transaction);
    }
}
